package jbit.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import sun.nio.cs.ext.TIS_620;

import jbit.constants.Constants;
import jbit.entity.Employee;
import jbit.util.PageBean;

import jbit.dao.ClaimVoucherDao;
import jbit.dao.ClaimVoucherDetailDao;
import jbit.entity.ClaimVoucher;
import jbit.entity.ClaimVoucherDetail;
import jbit.service.ClaimVoucherService;

public class ClaimVoucherServiceImpl implements ClaimVoucherService {
	
	private ClaimVoucherDao claimVoucherDao;
	private ClaimVoucherDetailDao claimVoucherDetailDao;
	
	public ClaimVoucher saveClaimVoucher(ClaimVoucher claimVoucher){
		ClaimVoucher newClaimVoucher=null;
		if(null==claimVoucher.getId()||0==claimVoucher.getId()||"".equals(claimVoucher.getId())){
			if(null==claimVoucher.getTotalAccount()||"".equals(claimVoucher.getTotalAccount())){
				claimVoucher.setTotalAccount(0d);
			}
			newClaimVoucher=this.claimVoucherDao.add(claimVoucher);
		}else{
			newClaimVoucher=this.claimVoucherDao.update(claimVoucher);
		}
		return newClaimVoucher;
	}
	
	public ClaimVoucher submitClaimVocher(ClaimVoucher claimVoucher,ClaimVoucherDetail claimVoucherDetail) throws Exception{
		ClaimVoucher oldClaimVoucher=claimVoucher;
		ClaimVoucher newClaimVoucher=null;
		
		if(oldClaimVoucher.getId()!=0){
			newClaimVoucher=this.claimVoucherDao.get(claimVoucher.getId());
			newClaimVoucher.setSysEmployeeByNextDealSn(oldClaimVoucher.getSysEmployeeByNextDealSn());//修改下一个审核者
			newClaimVoucher.setStatus(Constants.CLAIMVOUCHER_SUBMITTED);//修改状态
			newClaimVoucher=this.claimVoucherDao.update(newClaimVoucher);	
		}else{
			List<ClaimVoucherDetail> detaiList=new ArrayList<ClaimVoucherDetail>();
			detaiList.add(claimVoucherDetail);
			if(null==claimVoucher.getTotalAccount()||"".equals(claimVoucher.getTotalAccount())){
				claimVoucher.setTotalAccount(0d);
			}
			newClaimVoucher=this.claimVoucherDao.add(claimVoucher);
			claimVoucherDetail.setBizClaimVoucher(newClaimVoucher);
			this.claimVoucherDetailDao.add(claimVoucherDetail);
			newClaimVoucher.setTotalAccount(claimVoucherDetail.getAccount());
			newClaimVoucher=this.claimVoucherDao.update(newClaimVoucher);
			newClaimVoucher.setBizClaimVoucherDetails(this.getClaimVoucherDetailDao().getDetails(claimVoucher.getId()));
			
		}
		
		return newClaimVoucher;
	}
	
	public ClaimVoucher query(ClaimVoucher claimVoucher){
		claimVoucher=claimVoucherDao.getClaimVoucher(claimVoucher);
		return claimVoucher;
	}
	
	public ClaimVoucher addClaimVocherDetail(ClaimVoucherDetail claimVoucherDetail){
		ClaimVoucher claimVoucher=null;
		claimVoucher=claimVoucherDetail.getBizClaimVoucher();
		
		//如果获取主单ID，以前不存在主单则添加主单
		if(claimVoucher.getId()==null) 
			claimVoucher.setId(0);
		if(claimVoucher.getId()==0){
			//添加报销单到claimVoucher中，添加后获取新的claimVoucher（id不同）
			claimVoucher=claimVoucherDao.add(claimVoucher);
			//在claimVoucherDetail中设置主单为claimVoucher
			claimVoucherDetail.setBizClaimVoucher(claimVoucher);
			//添加报销单明细，添加到数据库中
			claimVoucherDetailDao.add(claimVoucherDetail);
			//给claimVocher的totalAccount放入总价钱
			claimVoucher.setTotalAccount(claimVoucherDetail.getAccount());	
		}else{
			//在claimVoucherDetail中设置主单为claimVoucher
			claimVoucherDetail.setBizClaimVoucher(claimVoucher);
			//添加报销单明细，添加到数据库中
			claimVoucherDetail=claimVoucherDetailDao.add(claimVoucherDetail);
			//获取总报销额
			double totalAccount=claimVoucherDetailDao.getTotalAcount(claimVoucher.getId());
			//在claimVoucher中添加总报销额
			claimVoucher.setTotalAccount(totalAccount);			
		}
		//更新claimVoucher
		claimVoucher=claimVoucherDao.update(claimVoucher);
		//在claimVoucher中追加所有的明细到set
		claimVoucher.getBizClaimVoucherDetails().addAll(claimVoucherDetailDao.getDetails(claimVoucher.getId()));
		
		return claimVoucher;
	}
	
	public ClaimVoucher delClaimVoucherDetail(Serializable id){
		//根据ID 找到报销单明细
		ClaimVoucherDetail claimVoucherDetail=claimVoucherDetailDao.get(id);
		//获得主单
		ClaimVoucher claimVoucher=claimVoucherDetail.getBizClaimVoucher();
		//删除主单中的明细
		claimVoucher.getBizClaimVoucherDetails().remove(claimVoucherDetail);
		//根据id删除detail中的记录
		claimVoucherDetailDao.deleteById(id);
		//根据主单id获取总报销额
		double totalAccount=claimVoucherDetailDao.getTotalAcount(claimVoucher.getId());
		//给主单设置总报销额
		claimVoucher.setTotalAccount(totalAccount);
		//更新主单
		claimVoucher=claimVoucherDao.update(claimVoucher);
		//清除主单中detail
		claimVoucher.getBizClaimVoucherDetails().clear();
		//在主单中增加明细
		claimVoucher.getBizClaimVoucherDetails().addAll(claimVoucherDetailDao.getDetails(claimVoucher.getId()));
		return claimVoucher;
	}
	

	// 员工查询报销单方法
    public PageBean queryForPage(int pageSize, int page,ClaimVoucher condition, Employee employee) {
        StringBuffer sb_hql = new StringBuffer("from ClaimVoucher c ");// 查询语句
        String hql;
        //根据查询条件组织查询语言
        if (condition != null) {
            sb_hql.append("where");
            if (!"".equals(employee.getSn())) {
                sb_hql.append("  c.sysEmployeeByCreateSn.sn=:creatorSn order by c.status asc c.createTime desc and  ");
            }
            String temp = sb_hql.toString();
            if (temp.contains("and")) {
                hql = temp.substring(0, temp.lastIndexOf("and")).trim();
            } else {
                hql = temp.substring(0, temp.lastIndexOf("where")).trim();
            }
        } else {
            hql = sb_hql.toString();
        }
        System.out.println(hql);
        //查询总记录数的查询语言
        String countHql = "select count(c.id) " + hql.substring(0, hql.lastIndexOf("order")).trim();
        System.out.println(countHql);

        int allRow = claimVoucherDao.getAllRowCount(countHql, condition, employee, null);// 总记录数
        int totalPage = PageBean.countTotalPage(pageSize, allRow);// 总页数
        final int offset = PageBean.countOffset(pageSize, page);// 当前页开始记录
        final int length = pageSize;// 每页记录数
        final int currentPage = PageBean.countCurrentPage(page);
        final int totalGroup = PageBean.countTotalGroup(totalPage);
        List<ClaimVoucher> list = claimVoucherDao.queryForPage(hql,
                offset, length, condition, employee, null);// "一页"的记录

        // 把分页信息保存到Bean中
        return setPageBean(pageSize,currentPage,allRow,totalPage,list,totalGroup);
    }

 // 把分页信息保存到Bean中
    private PageBean setPageBean(int pageSize,int currentPage,int allRow,int totalPage,List<ClaimVoucher> list,int totalGroup){
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(pageSize);
        pageBean.setCurrentPage(currentPage);
        pageBean.setAllRow(allRow);
        pageBean.setTotalPage(totalPage);
        pageBean.setList(list);
        pageBean.setTotalGroup(totalGroup);
        pageBean.init();
        return pageBean;
    }
    
    
    // 按日期查询功能
    public PageBean queryByDate(int pageSize, int page,
            ClaimVoucher condition, Employee employee) {
        StringBuffer sb_hql = new StringBuffer(
                "select distinct c from ClaimVoucher c,Employee e ");// 查询语句
        String hql = null;
        if (employee != null) {
            if (employee.getSysPosition().getNameCn().equals(
                    Constants.POSITION_FM)) {//部门经理
                sb_hql.append("where");
                if (!"".equals(employee.getSn()) && null != employee.getSn()) {
                    sb_hql.append("  e.sysDepartment.id=:departmentId  and ");
                }
                if (!"".equals(condition.getCreateTime())) {// 增加按日期查询条件
                    sb_hql.append("    c.createTime between :date1 and :date2  and");
                }
                if (!"".equals(condition.getStatus())) {
                    sb_hql.append(" c.status<>:status order by c.status asc c.createTime desc and");
                }
            } else if (employee.getSysPosition().getNameCn().equals(
                    Constants.POSITION_GM)//总经理
                    || employee.getSysPosition().getNameCn().equals(
                            Constants.POSITION_CASHIER)) {//财务
                sb_hql.append(" ,CheckResult cr where");
                if (!"".equals(employee.getSn()) && null != employee.getSn()) {
                    sb_hql.append("  c.sysEmployeeByNextDealSn.sn=e.sn and e.sn=:nextDealSn or (cr.sheetId=c.id and cr.sysEmployee.sn=e.sn and e.sn=:nextDealSn) ");
                }
                if (!"".equals(condition.getCreateTime())) {// 增加按日期查询条件
                    sb_hql.append(" and   c.createTime between :date1 and :date2  ");
                }
                if (1 == 1) {
                    sb_hql.append(" order by c.status asc c.createTime desc and");
                }
            } else if (employee.getSysPosition().getNameCn().equals(// 增加按日期查询功能
                    Constants.POSITION_STAFF)) {
                if (condition != null) {
                    sb_hql.append("where");
                    if (!"".equals(condition.getCreateTime())) {
                        sb_hql.append("  c.createTime between :date1 and :date2  and");
                    }
                    if (!"".equals(employee.getSn())) {
                        sb_hql.append("  c.sysEmployeeByCreateSn.sn=:creatorSn order by c.status asc c.createTime desc and  ");
                    }
                }
            }
            String temp = sb_hql.toString();
            if (temp.contains("and")) {
                hql = temp.substring(0, temp.lastIndexOf("and")).trim();
            } else {
                hql = temp.substring(0, temp.lastIndexOf("where")).trim();
            }
        } else {
            hql = sb_hql.toString();
        }
        System.out.println(hql);
        String newhql = hql.substring(0, hql.lastIndexOf("order")).trim();
        int num = newhql.toUpperCase().indexOf("FROM");
        String countHql = "select count(distinct c.id) " + newhql.substring(num, newhql.length());
        System.out.println(newhql);
        int allRow = 0;
        if (employee.getSysPosition().getNameCn().equals(Constants.POSITION_STAFF)) {// 增加按日期查询功能
            allRow = claimVoucherDao.getAllRowCount(countHql, condition, employee, "date");
        } else {
            allRow = claimVoucherDao.getAllRowCountM(countHql, condition, employee, "date");// 总记录数
        }
        int totalPage = PageBean.countTotalPage(pageSize, allRow);// 总页数
        final int offset = PageBean.countOffset(pageSize, page);// 当前页开始记录
        final int length = pageSize;// 每页记录数
        final int currentPage = PageBean.countCurrentPage(page);
        final int totalGroup = PageBean.countTotalGroup(totalPage);
        List<ClaimVoucher> list = null;
        if (employee.getSysPosition().getNameCn().equals(Constants.POSITION_STAFF)) {// 增加按日期查询功能
            list = claimVoucherDao.queryForPage(hql, offset, length, condition, employee, "date");// 传的参数中有“date”，代表执行按日期查询 ，"一页"的记录
        } else {
            list = claimVoucherDao.queryForPageM(hql, offset, length, condition, employee, "date");// 传的参数中有“date”，代表执行按日期查询
        }
        // 把分页信息保存到Bean中
        return setPageBean(pageSize,currentPage,allRow,totalPage,list,totalGroup);
    }
    
    
 // 部门经理查询已提交和审核后的报销单
    public PageBean queryClaimVoucher(int pageSize, int page,
            ClaimVoucher condition, Employee employee) {
    	// 查询语句
        StringBuffer sb_hql = new StringBuffer(
         "select distinct c from ClaimVoucher c,Employee e ");
        String hql = null;
        if (employee != null) {
        	// 当以部门经理身份登陆时执行的查询，
            // 查询本部门员工填写的不包含新创建的报销单
            if (employee.getSysPosition().getNameCn().equals(Constants.POSITION_FM)) {                                             
                sb_hql.append("where");
                if (!"".equals(employee.getSn()) && null != employee.getSn()) {
                    sb_hql.append("  e.sysDepartment.id=:departmentId  and ");
                }
                if (!"".equals(condition.getStatus())) {
                    sb_hql.append(" c.status<>:status order by c.status asc c.createTime desc and");
                }
            }
            // 当以总经理身份登陆时执行的查询，查询待审核人为当前登陆用户，
            // 或者当前登陆用户曾审核过
            else if (employee.getSysPosition().getNameCn().equals(Constants.POSITION_GM)                                          
                    || employee.getSysPosition().getNameCn().equals(Constants.POSITION_CASHIER)) {
                sb_hql.append(" ,CheckResult cr where");
                if (!"".equals(employee.getSn()) && null != employee.getSn()) {
                    sb_hql.append("  c.nextDealBy.sn=e.sn and e.sn=:nextDealSn " +
                    		"or (cr.sheetId=c.id and cr.sysEmployee.sn=e.sn and e.sn=:nextDealSn) " +
                    		"order by c.status asc c.createTime desc and");
                }
            }
            String temp = sb_hql.toString();
            if (temp.contains("and")) {
                hql = temp.substring(0, temp.lastIndexOf("and")).trim();
            } else {
                hql = temp.substring(0, temp.lastIndexOf("where")).trim();
            }
        } else {
            hql = sb_hql.toString();
        }
        System.out.println(hql);
        String newhql = hql.substring(0, hql.lastIndexOf("order")).trim();
        int num = newhql.toUpperCase().indexOf("FROM");
        String countHql = "select count(distinct c.id) " + newhql.substring(num, newhql.length());
        System.out.println(newhql);

        int allRow = claimVoucherDao.getAllRowCountM(countHql, condition, employee, null);// 总记录数
        int totalPage = PageBean.countTotalPage(pageSize, allRow);// 总页数
        final int offset = PageBean.countOffset(pageSize, page);// 当前页开始记录
        final int length = pageSize;// 每页记录数
        final int currentPage = PageBean.countCurrentPage(page);
        final int totalGroup = PageBean.countTotalGroup(totalPage);
        List<ClaimVoucher> list = claimVoucherDao
        	.queryForPageM(hql, offset, length, condition, employee, null);// "一页"的记录

        // 把分页信息保存到Bean中
        return setPageBean(pageSize,currentPage,allRow,totalPage,list,totalGroup);
    }
    
    
    public void removeClaimVoucher(ClaimVoucher claimVoucher){
    	this.claimVoucherDao.deletClaimVoucher(claimVoucher);
    }
    
    
    public ClaimVoucher modifyClaimVoucher(ClaimVoucher claimVoucher, ClaimVoucherDetail claimVoucherDetail, String type){
    	ClaimVoucher newClaimVoucher=null;
    	if("save".equals(type)){
    		newClaimVoucher=saveClaimVoucher(claimVoucher);
    	}
    	if("submit".equals(type)){
    		try {
				newClaimVoucher=submitClaimVocher(claimVoucher, claimVoucherDetail);
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	
    	
    	return newClaimVoucher;
    }
    
    
    
	public ClaimVoucherDao getClaimVoucherDao() {
		return claimVoucherDao;
	}

	public void setClaimVoucherDao(ClaimVoucherDao claimVoucherDao) {
		this.claimVoucherDao = claimVoucherDao;
	}

	public ClaimVoucherDetailDao getClaimVoucherDetailDao() {
		return claimVoucherDetailDao;
	}

	public void setClaimVoucherDetailDao(ClaimVoucherDetailDao claimVoucherDetailDao) {
		this.claimVoucherDetailDao = claimVoucherDetailDao;
	}
}
